package in.muton.edushare.components.messaging.api;

import in.muton.edushare.wicket.models.CayenneList;
import in.muton.edushare.wicket.models.CayenneModel;

import java.util.Date;
import java.util.List;

import org.apache.wicket.model.IModel;

import com.edushare.common.dao.MessagesDAO;
import com.edushare.common.orm.ORMInterface;
import com.edushare.common.vo.CourseInstances;
import com.edushare.common.vo.Departments;
import com.edushare.common.vo.Groups;
import com.edushare.common.vo.Messages;
import com.edushare.common.vo.Universities;
import com.edushare.common.vo.Users;

public class SystemMessage {
	public SystemMessage(ORMInterface orm, Users u, Universities univ,
			String message, CayenneList<Users> recipients) {
		this.orm = orm;
		this.userList = recipients;
		getMessageObj(message, u);
		messageVO.getObject().setReceiverId(univ.getUniversityId());
		messageVO.getObject()
				.setReceiverType(Messages.RECEIVER_TYPE_UNIVERSITY);
	}

	public SystemMessage(ORMInterface orm, Users u, CourseInstances course,
			String message, CayenneList<Users> recipients) {
		this.orm = orm;
		this.userList = recipients;
		getMessageObj(message, u);
		messageVO.getObject().setReceiverId(course.getCourseInstanceId());
		messageVO.getObject()
				.setReceiverType(Messages.RECEIVER_TYPE_COURSE);
	
	}

	public SystemMessage(ORMInterface orm, Users u, Departments dept,
			String message, CayenneList<Users> recipients) {
		this.orm = orm;
		this.userList = recipients;
		getMessageObj(message, u);
		messageVO.getObject().setReceiverId(dept.getDepartmentId());
		messageVO.getObject()
				.setReceiverType(Messages.RECEIVER_TYPE_DEPARTMENT);
	}

	public SystemMessage(ORMInterface orm, Users u, Groups group,
			String message, CayenneList<Users> recipients) {
		this.orm = orm;
		this.userList = recipients;
		getMessageObj(message, u);
		messageVO.getObject().setReceiverId(group.getGroupId());
		messageVO.getObject()
				.setReceiverType(Messages.RECEIVER_TYPE_GROUP);
	}

	public void send() {
		List<IModel<Users>> users = userList.getObject();
		for (IModel<Users> u : users) {
			messageVO.getObject().addToAllMessageRecipients(u.getObject());
		}
		orm.commitAllChanges();
	}

	private void getMessageObj(String message, Users user) {
		Messages m = new MessagesDAO(orm).getNewMessageObj();
		m.setCreationTimestamp(new Date());
		m.setMessage(message);
		m.setPrivacyType(Messages.PRIVACY_TYPE_PRIVATE);
		m.setUser(user);
		m.setUpdateTimestamp(new Date());
		m.setStatus(Messages.STATUS_ACTIVE);
		messageVO = new CayenneModel<Messages>(m);
	}

	private CayenneList<Users> userList = null;
	private IModel<Messages> messageVO = null;
	private ORMInterface orm = null;
}
